//
//  LLPImageDataManager.m
//  LLP
//
//  Created by psy on 12-10-12.
//  Copyright (c) 2012年 Porcellio. All rights reserved.
//

#import "LLPImageDataManager.h"
#import "LLPImageData.h"
#import "LLPUserDafaults.h"

static LLPImageDataManager* _myLLPImageDataManager = nil;
@implementation LLPImageDataManager
@synthesize imgDataDictionary = _imgDataDictionary;

#pragma mark - basic method
+ (LLPImageDataManager*)sharedImgDataManager{
    if (_myLLPImageDataManager == nil) {
        _myLLPImageDataManager = [[self alloc]init];
    }
    return _myLLPImageDataManager;
}

- (void)dealloc{
    [_imgDataDictionary release];
    [super dealloc];
}

- (id)init{
    self = [super init];
    if (self) {
        _imgDataDictionary = [[NSMutableDictionary alloc]init];
        [self loadData];
    }
    return self;
}

#pragma mark - 基础Image操作
- (void)addImage:(LLPImageData*)tmpImgData{
    [_imgDataDictionary setValue:tmpImgData forKey:tmpImgData.imgName];
    [self saveData];
}
- (void)deleteImage:(LLPImageData*)tmpImgData{
    [_imgDataDictionary removeObjectForKey:tmpImgData.imgName];
    [self saveData];
}
- (void)modifyImage:(LLPImageData*)tmpImgData{
    [_imgDataDictionary setValue:tmpImgData forKey:tmpImgData.imgName];
    [self saveData];
}

#pragma mark - 存储和读取 IO操作
- (void) loadData{
    //list存在一个dictory里面，里面有每一个图片的name，file地址等属性
    NSDictionary* tmpDic = [LLPUserDafaults imgDataDictionary];
    NSArray* tmpNameList = [tmpDic allKeys];
    for (NSString* tmpName in tmpNameList) {
        NSDictionary* tmpImgDic = [tmpDic valueForKey:tmpName];
        LLPImageData* tmpImgData = [[[LLPImageData alloc]initWithDic:tmpImgDic]autorelease];
        [_imgDataDictionary setValue:tmpImgData forKey:tmpName];
    }
}
- (void) saveData{
    [LLPUserDafaults saveImageDataDictionary:[self convertToDic]];
    
    NSArray* tmpNameList = [_imgDataDictionary allKeys];
    for (NSString* tmpName in tmpNameList) {
        LLPImageData* tmpImgData = [_imgDataDictionary valueForKey:tmpName];
        [tmpImgData saveImgArray];
    }
}

- (NSDictionary*)convertToDic{
    NSMutableDictionary* tmpDic = [NSMutableDictionary dictionary];
    NSArray* tmpNameList = [_imgDataDictionary allKeys];
    for (NSString* tmpName in tmpNameList) {
        LLPImageData* tmpImgData = [_imgDataDictionary valueForKey:tmpName];
        [tmpDic setValue:tmpImgData.convertToDic forKey:tmpName];
    }
    return tmpDic;
}

@end
